﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.datatype;
using umbraco.interfaces;
using System.Data;
using System.Xml;

namespace Nibble.Umb.Locator.Datatypes.GoogleMapsGeocoder
{
    public class GoogleMapsGeocoderPrevalueEditor : PlaceHolder, IDataPrevalue
    {
        private GoogleMapsGeocoderDataType _dataType;
        private string _configFile = "/config/Nibble.Umb.Locator.config";
        private GridView _grid;

        public GoogleMapsGeocoderPrevalueEditor(GoogleMapsGeocoderDataType dataType)
        {
            this._dataType = dataType;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _grid = new GridView();
            _grid.AutoGenerateColumns = false;

            BoundField urlField = new BoundField();
            urlField.DataField = "url";
            urlField.HeaderText = "Web site URL";
            _grid.Columns.Add(urlField);

            BoundField valueField = new BoundField();
            valueField.DataField = "value";
            valueField.HeaderText = "Google Maps API Key";
            _grid.Columns.Add(valueField);

            TemplateField deleteField = new TemplateField();

            deleteField.HeaderTemplate = new GridDeleteLinkButtonTemplate(DataControlRowType.Header);
            deleteField.ItemTemplate = new GridDeleteLinkButtonTemplate(DataControlRowType.DataRow);

            _grid.Columns.Add(deleteField);

            _grid.AutoGenerateDeleteButton = false;
            _grid.RowDeleting += new GridViewDeleteEventHandler(_grid_RowDeleting);
            _grid.BorderColor = System.Drawing.Color.White;
            loadData();

            this.Controls.Add(_grid);

        }



        void _grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {


            XmlDocument config = new XmlDocument();
            config.Load(HttpContext.Current.Server.MapPath(_configFile));

            config.SelectSingleNode("/config").RemoveChild(config.SelectSingleNode("/config").ChildNodes[e.RowIndex]);

            config.Save(HttpContext.Current.Server.MapPath(_configFile));

            loadData();

        }
        protected override void Render(HtmlTextWriter writer)
        {

            writer.Write("<table>");
            writer.Write("<tr>");
            writer.Write("<td colspan=\"2\"><strong>Add new</strong> (<a href=\"http://code.google.com/apis/maps/signup.html\" target=\"_blank\">signup</a>):</td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<th style=\"width:150px\">Web site URL:</th>");
            writer.Write("<td><input id=\"domain\" name=\"domain\" class=\"umbEditorTextField\" /></td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<th style=\"width:150px\">Google Maps API Key:</th>");
            writer.Write("<td><input id=\"apiKey\" name=\"apiKey\"  class=\"umbEditorTextField\" /></td>");
            writer.Write("</tr>");
            writer.WriteLine("</table>");
            writer.Write("<br/>");
            writer.Write("<strong>Overview:</strong><br/>");
            _grid.RenderControl(writer);


        }

        public void Save()
        {
            this._dataType.DBType = DBTypes.Nvarchar;

            if (HttpContext.Current.Request["domain"] != null && HttpContext.Current.Request["apiKey"] != null)
            {
                if (HttpContext.Current.Request["domain"].Length > 0 && HttpContext.Current.Request["apiKey"].Length > 0)
                {
                    XmlDocument config = new XmlDocument();
                    config.Load(HttpContext.Current.Server.MapPath(_configFile));

                    XmlNode newNode = config.CreateElement("key");
                    XmlAttribute urlAttribute = config.CreateAttribute("url");
                    urlAttribute.Value = HttpContext.Current.Request["domain"];

                    newNode.Attributes.Append(urlAttribute);

                    XmlAttribute valueAttribute = config.CreateAttribute("value");
                    valueAttribute.Value = HttpContext.Current.Request["apiKey"];

                    newNode.Attributes.Append(valueAttribute);

                    config.SelectSingleNode("/config").AppendChild(newNode);

                    config.Save(HttpContext.Current.Server.MapPath(_configFile));

                    loadData();

                }
            }
        }


        private void loadData()
        {
            DataSet configDataSet;
            string filePath = HttpContext.Current.Server.MapPath(_configFile);
            configDataSet = new DataSet();
            configDataSet.ReadXml(filePath);
            _grid.DataSource = configDataSet.Tables[0].DefaultView;
            _grid.DataBind();
        }

        public Control Editor
        {
            get
            {
                return this;
            }
        }
    }

    public class GridDeleteLinkButtonTemplate : ITemplate
    {
        private DataControlRowType templateType;


        public GridDeleteLinkButtonTemplate(DataControlRowType type)
        {
            templateType = type;

        }

        public void InstantiateIn(System.Web.UI.Control container)
        {
            switch (templateType)
            {
                case DataControlRowType.Header:
                    Literal lc = new Literal();
                    lc.Text = "<b>Delete</b>";
                    container.Controls.Add(lc);
                    break;
                case DataControlRowType.DataRow:
                    LinkButton lb = new LinkButton();
                    lb.DataBinding += new EventHandler(this.lb_DataBinding);
                    lb.Text = "Delete this key";
                    lb.OnClientClick = "return confirm('Are you sure you want to delete this key');";
                    container.Controls.Add(lb);
                    break;
                default:
                    break;
            }
        }



        private void lb_DataBinding(Object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            GridViewRow row = (GridViewRow)lb.NamingContainer;
            lb.CommandArgument = row.RowIndex.ToString();
            lb.CommandName = "delete";
        }

    }
}
